﻿using System;
using System.Web;
using System.Web.SessionState;

using Manager;

    /// <summary>
    ///  后台处理基类，含权限验证功能
    /// </summary>
public class BaseHandler : IHttpHandler, IRequiresSessionState
{
    /// <summary>
    /// 当前上下文
    /// </summary>
    private HttpContext _context;
    public HttpContext Context
    {
        get { return _context; }
        set { _context = value; }
    }

    /// <summary>
    /// 当前登录用户
    /// </summary>
    private SessionUser _currUser;
    public SessionUser CurrentUser
    {
        get { return _currUser; }
        set { _currUser = value; }
    }

    #region IHttpHandler接口实现
    public virtual void ProcessRequest(HttpContext context)
    {
        // 上下文设置
        Context = context;
    }

    #region 验证功能

    public enum ERole
    {
        /// <summary>
        /// 游客
        /// </summary>
        Anyone = 0,

        /// <summary>
        /// 普通用户
        /// </summary>
        User = 1,

        /// <summary>
        /// 管理员
        /// </summary>
        Admin = 99
    }

    /// <summary>
    /// 验证是否有权限,只验证角色
    /// </summary>
    /// <param name="desiredRole">允许的角色</param>
    /// <returns>验证结果</returns>
    public bool Validate(ERole desiredRole)
    {
        SessionUser u = Context.Session[Constants.SESS_USER_KEY] as SessionUser;

        if (u == null)
        {
            return false;
        }

        // 管理员拥有所有权限
        if (u.RoleId == (int)ERole.Admin)
        {
            return true;
        }

        //拥有相应权限才能通过验证
        if (u.RoleId == (int)desiredRole)
        {
            return true;
        }
        else    // CurrentUser.RoleId != DesiredRole
        {
            return false;
        }
    }

    /// <summary>
    /// 验证是否有权限,要访问指定ID的用户信息时,验证只允许本人的ID通过
    /// </summary>
    /// <param name="desiredRole">允许的角色</param>
    /// <param name="targetId">要访问的ID</param>
    /// <returns>验证结果</returns>
    public bool Validate(ERole desiredRole, string requestId)
    {

        SessionUser u = Context.Session[Constants.SESS_USER_KEY] as SessionUser;

        if (u == null)
        {
            return false;
        }

        // 管理员拥有所有权限
        if (u.RoleId == (int)ERole.Admin)
        {
            return true;
        }

        //拥有相应权限才能通过验证,本人只能访问自己所拥有的权限
        if (u.RoleId == (int)desiredRole && u.ID == requestId)
        {
            return true;
        }
        else    // u.RoleId != DesiredRole || u.ID != requestID
        {
            return false;
        }
    }

    #endregion


    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    #endregion
}